import { upperFirst } from 'lodash-es';
import { getPlugins } from './AMapUtils.js';
import { tap } from '../../../utils/index.js';

export class AMapPolyEditor {
  constructor(map, option) {
    this.map = map;
    this.option = (typeof option === 'object' && option) || {};
    this.listeners = ['addnode', 'adjust', 'removenode', 'end'];
  }
  async start(poly) {
    if (!AMap.PolyEditor) {
      await getPlugins(['AMap.PolyEditor']);
    }
    if (this.polyEditor) {
      this.polyEditor.close();
    }
    this.polyEditor = new AMap.PolyEditor(this.map, poly);
    this.listeners.forEach((eventName) => {
      this.polyEditor.on(eventName, (e) => {
        tap(this.option, `on${upperFirst(eventName)}`, e);
      });
    });
    this.polyEditor.open();
    tap(this.option, 'onStart');
  }
  stop() {
    if (this.polyEditor) {
      this.polyEditor.close();
    }
    tap(this.option, 'onEnd');
  }
}
